package com.nl.controller.xuyi.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nl.controller.common.util.AES;
import com.nl.controller.web.global.GlobalConst;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.nl.controller.common.model.BaseResult;
import com.nl.controller.web.bean.BdResult;
import com.nl.controller.web.bean.SmsAllStation;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.bean.XuYiStation;
import com.nl.controller.web.mapper.SmsAreaMapper;
import com.nl.controller.web.service.SmsInterfacesService;
import com.nl.controller.web.util.FileUtil;
import com.nl.controller.web.util.HttpClientUtil;
import com.nl.controller.xuyi.mapper.XuYiStationMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class XuYiStationService {
	@Autowired
	SmsInterfacesService smsInterfacesService;
	@Autowired
	XuYiStationMapper xuYiStationMapper;
	
	@Autowired
	SmsAreaMapper smsAreaMapper;	
	
	public int saveStationFileData(String path,String operatorTel){
		int dataCount=0;
		List list;
		SmsBaseStation stationInfo=new SmsBaseStation();
		String[] arr;
		String x = "";
		String y = "";
		list = FileUtil.readCSV(path);
		for(int i=0;i<list.size();i++){
			try {
				arr=list.get(i).toString().split(","); 	
				stationInfo.setStationName(arr[0]);
				stationInfo.setStationId(arr[1]);
				String url = "http://api.map.baidu.com/ag/coord/convert";
				Map<String, String> querys = new HashMap<String, String>();
				querys.put("from", "0");
				querys.put("to", "4");
				querys.put("x", arr[2]);
				querys.put("y", arr[3]);
				BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
				if ("0".equals(sendGet.getRetCode())) {
					BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class);
					if ("0".equals(data.getError())) {
						x = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
						y = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
					}
				}
				stationInfo.setGpsLng(arr[2]);
				stationInfo.setGpsLat(arr[3]);
				stationInfo.setBdLng(x);
				stationInfo.setBdLat(y);
				stationInfo.setOperatorTel(operatorTel);
				//备注
				if(arr.length>4){
					stationInfo.setRemark(arr[4]);
				}

				int result=xuYiStationMapper.stationAdd(stationInfo);
				if(result==1){
					dataCount++;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.info("数据插入异常"+stationInfo.getStationName());
				return -1;
			}

		}
		//nt result= SmsMgrTemplateInfoMapper.saveFileData()
		return dataCount;
	}
	
	
	public int stationAdd(String stationName,String stationId,String lng,String lat,String remark,String operatorTel){
		int result = 0;
		try {
			SmsBaseStation stationInfo=new SmsBaseStation();
			
			/*String lngLat = smsInterfacesService.GPSToBd(lng, lat);
			String bdLng = "";
			String bdLat = "";
			bdLng = lngLat.split(",")[0];
			bdLat = lngLat.split(",")[1];*/
			String url = "http://api.map.baidu.com/ag/coord/convert";
			Map<String, String> querys = new HashMap<String, String>();
			querys.put("from", "0");
			querys.put("to", "4");
			querys.put("x", lng);
			querys.put("y", lat);
			stationInfo.setGpsLng(lng);
			stationInfo.setGpsLat(lat);
			BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
			if ("0".equals(sendGet.getRetCode())) {
				BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class);
				if ("0".equals(data.getError())) {
					lng = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
					lat = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
				}
			}
			stationInfo.setStationName(stationName);
			stationInfo.setStationId(stationId);

			stationInfo.setBdLng(lng);
			stationInfo.setBdLat(lat);
			stationInfo.setRemark(remark);
			stationInfo.setOperatorTel(operatorTel);
			
			
			result = xuYiStationMapper.stationAdd(stationInfo);	
			
		} catch (Exception e) {
			e.printStackTrace();
			log.info("坐标转化异常："+ e.toString());
			result = -1;
		}
		return result;
	}
	
	
	
	public List<String> findStationNameLike(String regionName,String stationName) {
		List<String> regionNameList = new ArrayList<String>();
		regionNameList= xuYiStationMapper.findStationNameLike(regionName,stationName);
		return regionNameList;
	}
	
	
	public PageInfo<SmsBaseStation> findXuYiStationsList(int page,int limit,String regionName,String stationName,String stationId) {
		PageHelper.startPage(page, limit);
		List<SmsBaseStation> xuYiStationList = new ArrayList<SmsBaseStation>();
		xuYiStationList= xuYiStationMapper.findXuYiStationsList(regionName,stationName,stationId);
		PageInfo<SmsBaseStation> pageInfo = new PageInfo<SmsBaseStation>(xuYiStationList);
		return pageInfo;
	}
	
	public PageInfo<SmsBaseStation> findXuYiStationsList2(int page,int limit,String stationId,String stationName,String alreadyRelate) {
		List<SmsBaseStation> regionNameList = new ArrayList<SmsBaseStation>();
		PageHelper.startPage(page, limit);
		String[] alreadyRelateList = null;
		List<String> alreadyRelateList2 = null;
		if(""!=alreadyRelate&&null!=alreadyRelate){
			alreadyRelateList = alreadyRelate.split(",");
			alreadyRelateList2 = new ArrayList<String>();
			for(String region:alreadyRelateList){
				alreadyRelateList2.add(region);
			}
		}
		Long startTime = System.currentTimeMillis();
		regionNameList= xuYiStationMapper.findXuYiStationsList2(stationId,stationName,alreadyRelateList2);
		Long endTime = System.currentTimeMillis();
		System.out.println("cost------"+(endTime-startTime));
		PageInfo<SmsBaseStation> pageInfo = new PageInfo<SmsBaseStation>(regionNameList);
		return pageInfo;
	}
	
	public int deleteStation(String stationId) {
		int result =0;
		try {
			 result = xuYiStationMapper.deleteStation(stationId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public SmsBaseStation findStationById(String stationId){
		SmsBaseStation stationInfo = new SmsBaseStation();
		
		try {
			stationInfo = xuYiStationMapper.findStationById(stationId);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		
		return stationInfo;
		
	}

	public int stationModify(String stationId,String gpsLng,String gpsLat,String stationName,String remark,String operatorTel){
		int result = 0;
		String bdLng = "";
		String bdLat = "";
		try {
			SmsBaseStation stationInfo = new SmsBaseStation();
			String url = "http://api.map.baidu.com/ag/coord/convert";
			Map<String, String> querys = new HashMap<String, String>();
			querys.put("from", "0");
			querys.put("to", "4");
			querys.put("x", gpsLng);
			querys.put("y", gpsLat);

			BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
			if ("0".equals(sendGet.getRetCode())) {
				BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class);
				if ("0".equals(data.getError())) {
					bdLng = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
					bdLat = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
				}
			}

			stationInfo.setGpsLng(gpsLng);
			stationInfo.setGpsLat(gpsLat);
			stationInfo.setBdLng(bdLng);
			stationInfo.setBdLat(bdLat);
			stationInfo.setStationId(stationId);
			stationInfo.setStationName(stationName);
			stationInfo.setRemark(remark);
			stationInfo.setOperatorTel(operatorTel);
			
			result = xuYiStationMapper.stationModify(stationInfo);	
		} catch (Exception e) {
			e.printStackTrace();
			result = -1;
		}
		return result;
	}
	
	
	public int stationRelateAdd(String regionName, String stationList, String operatorTel) {
		int result =0;
		String alreadyRelateStations;
		try {
			alreadyRelateStations = xuYiStationMapper.findRelStationByRegion(regionName);
			if(""!=alreadyRelateStations&&null!=alreadyRelateStations){
				xuYiStationMapper.deleteRelateStation(regionName,operatorTel);
			}
			result= xuYiStationMapper.stationRelateAdd(regionName,stationList,operatorTel);
		} catch (Exception e) {
			log.info("基站关联点位发生异常");
			e.printStackTrace();
		}
		return result;
	}
	
	public String findRelStationByRegion(String regionName) {
		String relStaionList = "";
		try {
			relStaionList = xuYiStationMapper.findRelStationByRegion(regionName);
		} catch (Exception e) {
			log.info("根据点位查询已关联的基站信息发生异常"+e.toString());
			e.printStackTrace();
		}
		return relStaionList;
	}
	
	
	public String findRelStationByRegion2(List<String> pathRegionNameList) {
		String[] eachStationsList;
		String eachStations = "";
		String relStaionList = "";
		String[] pathRegionSplit;
		String pathName = "";
		String regionName = "";
		List<String> distinctStationList = new ArrayList<String>() ;
		
		try {
			if(!CollectionUtils.isEmpty(pathRegionNameList)){
				for(String pathRegionName : pathRegionNameList){
					if(StringUtil.isNotEmpty(pathRegionName)){
						pathRegionSplit = pathRegionName.split("-");
						if(null!=pathRegionSplit&&pathRegionSplit.length>1){
							pathName = pathRegionSplit[0];
							regionName = pathRegionSplit[1];
							eachStations = xuYiStationMapper.findRelStationByRegion(regionName);
							if(StringUtil.isNotEmpty(eachStations)){
								eachStationsList = eachStations.split(",");
								if(null!=eachStationsList&&eachStationsList.length>0){
									for(String eachStationId : eachStationsList){
										if(!distinctStationList.contains(eachStationId)){
											distinctStationList.add(eachStationId);
										}else{
											log.info("重复数据，stationId:"+eachStationId);
										}
									}
								}							
							}
						}
					}
				}
				
			}
			
			
			//封装数据返给前台
			for(String distinctStation:distinctStationList){
				if(StringUtil.isNotEmpty(distinctStation)){
					if(!"".equals(relStaionList)){
						relStaionList =relStaionList +","+ distinctStation;
					}else{
						relStaionList = distinctStation;
					}
				}
				
			}
		} catch (Exception e) {
			log.info("根据点位名称查询关联基站发生异常");
			e.printStackTrace();
		}
		
		
		
		log.info("----"+relStaionList);

		return relStaionList;
	}
	

}
